/**
 * 模仿jquery_validate.js 数据验证
 * author:luoyouhua
 */
 
/**验证表单数据function
 * example
 * validate.addvalidte(util.$("frm01"),{
        rules:{
           musicName:{checkNull:true},
           musicPathbtn_input:{checkNull:true,suffix:/.mp3|.wav|.wma/i},
           musicLrcbtn_input:{suffix:/.lrc|.wrc|.ksc/i},
           musicPaid_input:{suffix:/.mp3|.wav|.wma/i},
           musicPrice:{checkNull:true,isFloat:true},
           
           },
	    message:{
           musicName:{checkNull:'必填项'},
           musicPathbtn_input:{checkNull:'必填项',suffix:'请选择mp3,wav,wma等音乐文件'},
           musicLrcbtn_input:{suffix:'请选择lrc,wrc,ksc等歌词文件'},
           musicPaid_input:{suffix:'请选择mp3,wav,wma等音乐文件'},
            musicPrice:{checkNull:'请输入',isFloat:"必须是数字"}
	    }
 * 
 * 
 * */ 
String.prototype.trim = function(){
   return this.replace(/(^\s*)|(\s*$)/g,"");
}
var Fun = {
	  checkNull:function(o){
	    var th = o.elm;
	  	var b = !(th.value.length==0);
	    return b;
	  },
	  email:function(o){
	     var th = o.elm;
	     if(th.value.length==0){
	       return true;
	     }
	     var b = /^([a-zA-Z0-9_\-\\.])+@\w+\..+$/.test(th.value);
	     return b;
	  },
	  minlength:function(o){
	     var th = o.elm,v = o.v;
	     return th.value.trim().length>=v;
	  },
	  maxlength:function(o){
	    var th = o.elm,v=o.v;
	    return th.value.length<=v;
	  },
	  maxLength:function(o){//最大字节数
	    var th = o.elm,v = o.v;
	    return th.value.replace(/[\u4e00-\u9fa5]/,"**").length<=v;
	  },
	  equals:function(o){//密码比较
	    var th = o.elm; var eq = o.elm.form[""+o.v+""];
	    return th.value == eq.value;
	  },
	  isurl:function(o){//url验证
	    var th = o.elm;
	    if(th.value.length==0){
	      return true;
	    }
	    return th.value.match(/(?:http|https):\/\/[^\.]+\..+$/i);
	  },
	  suffix:function(o){//后缀名判断
	    var th = o.elm,exp = o.v;
	    if(th.value.length==0){return true;}
	    return th.value.match(exp);
	  },
	  isImgFile:function(o){//是否是图片文件
	    var file = o.elm;
	    if(file.value.length==0){
	      return true;
	    }
	    return file.value.match(/.jpg|.gif|.png|.bmp/i);
	  },
	  isNumber:function(o){
		  var inp = o.elm;
		    if(inp.value.length==0){
		      return true;
		    }
		  return /^[0-9]*$/.test(inp.value); 
	  },
	  isFloat:function(o){
		  var inp = o.elm;
		    if(inp.value.length==0){
		      return true;
		    }
		  return !isNaN(inp.value); 
	  },
	  idCard:function(o){//验证是否是身份证 第一位不为0，2-17位是数字，最后一位可数字、可X 此处依赖IdCard.js
		  var th = o.elm;
		    if(th.value.length==0){
		      return true;
		    }
		    //此处依赖IdCard.js
		    return th.value.match(/^[1-9]\d{16}[\d|x|X]$/);
	  }
	};
function getMessage(e,n){
   try{
     return message[""+e.name+""][""+n+""]||message[""+e.name+""]||"";
   }catch(e){
     return '&nbsp;&nbsp;&nbsp;';
   }
   
}

/**错误信息提示*/
var message={
	  checkNull:"此项为必填项!",
	  email:"请正确输入您的email地址!",
	  equals:"两次输入的密码不一致"
}
/**错误信息处理方法*/
var vali_info={
  errorPlacement:function(e,m){
	var tag = e.getAttribute('warn');
	var p = e.getAttribute('proxy');
	if(p){
	 var o=document.getElementById(p);
	 o&&(o.style.backgroundColor="#ffcccc");
	}
	e.style.backgroundColor="#ffcccc";
	/**
    if(tag!='true'){
      e.setAttribute('warn','true');
      var div = util.cElem('label',{className:'error',cssText:'color:#ff6666;',id:e.name+'_error'},m);
      insertAfter(div,e);
    }*/
  },
  success:function(e){
	 
	  var p = e.getAttribute('proxy');
		if(p){
		 var o=document.getElementById(p);
		 o&&(o.style.backgroundColor="");
		}
	 e.style.backgroundColor="";
	  /**
	  var o = util.$(e.name+'_error');
		o && o.parentNode && (o.parentNode.removeChild(o));
		e.setAttribute('warn','false');
	  e.style.backgroundColor="#FFF";
      */
  }
}

/**给表单添加验证事件*/
var validate = function(fm,o){
   var extend = function(s,t){for(var p in t){s[p]=t[p]}},onsubmit,vali_form,vali_o//from 表单onsumit的时候调用的方法
   return {
     addvalidte:function(fm,o){
           if((!o)||(!fm)) return;
           vali_form = fm,vali_o = o;
		   var r = fm.elements; var rules = o.rules;
		   ext(message,o.message);//继承报错信息
		   ext(vali_info,{errorPlacement:o.errorPlacement,success:o.success});
		   if(rules){
			    var sumit = new Vali_fun();
			    each(r,function(e){
				  var rule = rules[e.name];
			      if(rule){
					 var hander = new Vali_fun();
			         for(var p in rule){
			             if(p!='event'){
				             if(p=="ajax"){
				                hander._push({fn:rule[p],elm:e,p:p,v:rule[p]});//ajax验证
				             }else{
				             	hander._push({fn:Fun[""+p+""],elm:e,p:p,v:rule[p]});//fn:验证function elm:验证的表单元素 p:验证名(emial checkNull..) v:rule[p] 值
				                sumit._push({fn:Fun[""+p+""],elm:e,p:p,v:rule[p]});
				             }
			             }
			         }
					 listen.addEvent(e,(rule.event?rule.event:"blur"),hander.createFun());
			      }
			   })
			   onsubmit = sumit.createFun();
		   }
     },
     re_addvalidte:function(){
        validate.addvalidte(vali_form,vali_o);
     },
     getSubmit:function(){
       return onsubmit;
     },
     submit:function(th){
    	 alert(th);
    	 if(validate.getSubmit()()){
    		 
    		 //if(confirm("确定提交表单?")){
    			 vali_form.submit();
    			 th&&(th.disabled='disabled');
    		 //}
    	 }
    	 
     }
     //
   }
}();
	/**表单事件执行方法*/
	function Vali_fun(){
	    this.vali = true;
	    this.fnr = [];
		this._push = function(o){
		   if(typeof o.fn=="function"){
		      this.fnr.push(o);
		   }
		};
		this.createFun = function(){
		   var r = this.fnr;
		   return function(){
             var b = true,elm;
			 for(var i=0,o;o=r[i];i++){
		        b = o.fn(o);
		        (i==0)&&(elm=o.elm)
				if(!b&&(o.p!="ajax")){
				  vali_info.errorPlacement(o.elm,getMessage(o.elm,o.p));break;
				};
		     }
		     b&&(vali_info.success(elm));
		     return b;
		   }
		}
	}
	
   /**each tool*/
   function each(r,fn){
      for(var i=0;i<r.length;i++){
         var rlt = fn(r[i],i);
         if(rlt!=undefined){ return rlt;}
      }
   }
   /**extends tool*/
   function ext(f,s){
      if((!f)||!(s))return;
      for(var p in s){
        if(s[p]){f[p] = s[p];}
      }
   }
   /**listen tool*/
	var listen = {
	  addEvent:function(target,t,fn){
	     if(target.addEventListener){
	        target.addEventListener(t,fn,false);
	     }else if(target.attachEvent){
	        target.attachEvent('on'+t,fn);
	     }else{
	        target['on'+t] = fn;
	     }
	  },
	  removeEvent:function(target,t,fn){
	     if(target.removeEventListener){
	        target.removeEventListener(t,fn,false);
	     }else if(target.detachEvent){
	        target.detachEvent('on'+t,fn);
	     }else{
	        target['on'+t] = null;
	     }
	  }
	}